package com.wanmait.gohome.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wanmait.gohome.mapper.CommentMapper;
import com.wanmait.gohome.mapper.TaskMapper;
import com.wanmait.gohome.mapper.UserinfoMapper;
import com.wanmait.gohome.pojo.*;
import com.wanmait.gohome.service.CommentService;
import com.wanmait.gohome.service.TaskProcessService;
import com.wanmait.gohome.service.TaskService;
import com.wanmait.gohome.util.Pager;
import com.wanmait.gohome.util.SysContext;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;

@Service
@Transactional
public class TaskServiceImpl implements TaskService {
    @Resource
    private RedisTemplate<String,String> redisTemplate;
    @Resource
    private HttpSolrClient client;

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private TaskMapper taskMapper;

    @Resource
    private UserinfoMapper userinfoMapper;
    @Override
    public void insert(Task object) {

    }

    @Override
    public void update(Integer id) {

    }

    @Override
    public void delete(Integer id) {

    }

    @Override
    public void delete(String ids) {

    }

    @Override
    public List<Task> findAll() {
        return null;
    }

    /**
     * 根据ID查找发布的任务 ，显示到显示页中.
     * @param id
     * @return
     */
    @Override
    public Task findById(Integer id) {
        Task task=taskMapper.findById(id);
       return task;
    }

    /**
     * 修改查看任务的浏览数
     * @param id
     */
    @Override
    public void updateBrowse(Integer id)
    {
        taskMapper.updateBrowse(id);
        Double browseCount = redisTemplate.opsForZSet().score("todayHotTasks",id+"");
        if(browseCount==null)
        {
            redisTemplate.opsForZSet().add("todayHotTasks",id+"",1);
        }
        else
        {
            redisTemplate.opsForZSet().add("todayHotTasks",id+"",browseCount+1);
        }
    }

    /**
     *
     * @param count
     * @return   今日最热任务
     */
    @Override
    public List<Task> findTodayHot(int count) {
        Set<String> idSet = redisTemplate.opsForZSet().reverseRange("todayHotTasks",0,count);
        if(idSet.size()==0){
            List<Task> tasks = taskMapper.selectByInputTime();
            return tasks;
        }else{
            List<Task> tasks = new ArrayList<>();
            for (String id:idSet)
            {
                Task task = taskMapper.selectListById(Integer.parseInt(id));
                tasks.add(task);
            }
            List<Task> tasks1 = taskMapper.selectByInputTime();
            tasks1.forEach(task -> tasks.add(task));
            return tasks;
        }
    }

    /**
     *   清空 redis  今日浏览数据
     */
    @Override
    public void clearTodayHot() {
        redisTemplate.delete("todayHotTasks");
    }

    @Override
    public int getTaskCount() {
        return taskMapper.getTaskCount();
    }

    @Override
    public int getFinishCount() {
        return taskMapper.getFinishCount();
    }

    @Override
    public PageInfo<Task> passTask() {
        int pageNum=SysContext.getPageNum();
        int pageSize=5;
        try {
            //pageSize = Integer.parseInt();//数据库里取
        } catch (NumberFormatException e) {
            pageSize=10;
        }
        PageHelper.startPage(pageNum,pageSize);//pageSize
        List<Task> taskPasses=taskMapper.selectAllPass();
        PageInfo<Task> pageInfo = new PageInfo<>(taskPasses, 5);
        return pageInfo;
    }

    @Override
    public PageInfo<Task> finishTask() {
        int pageNum=1;
        int pageSize=5;
        try {
            //pageSize = Integer.parseInt();//数据库里取
        } catch (NumberFormatException e) {
            pageSize=10;
        }
        PageHelper.startPage(pageNum,pageSize);//pageSize
        List<Task> finish=taskMapper.selectFinish();
        PageInfo<Task> pageInfo = new PageInfo<>(finish, 5);
        return pageInfo;
    }

    //通过
    @Override
    public void updatePass(Integer id) {
      taskMapper.updatePass(id);
    }

    @Override
    public void updateFinish(Integer id) {
    taskMapper.updateFinsh(id);
    }

    //拒绝
    @Override
    public void updateRefuse(Integer id) {
    taskMapper.updateRefuse(id);
    }

    @Override
    public void updateFinishRefuse(Integer id) {
    taskMapper.updateFinishRefuse(id);
    }


    @Override
    public PageInfo<Task> findPage() {
        return null;
    }

    @Override
    public List<Task> findAll(Task object) {
        return null;
    }

    @Override
    public PageInfo<Task> findPage(Task object) {
        return null;
    }

    /**
     * 查询所有的任务
     * @param
     * @return
     */
    @Override
    public PageInfo<Task> selectTask() {
         int pageNum= SysContext.getPageNum();
         int pageSize=5;
        try {
            //pageSize = Integer.parseInt();//数据库里取
        } catch (NumberFormatException e) {
            pageSize=10;
        }
        PageHelper.startPage(pageNum,pageSize);//pageSize
        List<Task> tasks=taskMapper.selectTask();
        PageInfo<Task> pageInfo = new PageInfo<>(tasks, 5);
        return pageInfo;
    }


    /**
     *
     * @param userId   个人中心  查看发布的任务
     * @return
     */
    @Override
    public PageInfo<Task> findByUserId(Integer userId) {
        int pageNum = SysContext.getPageNum();
        int pageSize = 5;
        PageHelper.startPage(pageNum,pageSize);
        List<Task> tasks= taskMapper.findByUserId(userId);
        PageInfo<Task> pageInfo = new PageInfo<>(tasks,5);
        return pageInfo;
    }


    /**
     *
     * @param userId   个人中心  查看接收的任务
     * @return
     */
    @Override
    public PageInfo<Task> selectByUserId(Integer userId) {
        int pageNum = SysContext.getPageNum();
        int pageSize = 5;
        PageHelper.startPage(pageNum,pageSize);
        List<Task> tasks= taskMapper.selectByUserId(userId);
        PageInfo<Task> pageInfo = new PageInfo<>(tasks,5);
        return pageInfo;
    }

    @Override
    public PageInfo<Task> selectAllTask() {
        int pageNum = SysContext.getPageNum();
        int pageSize = 5;
        PageHelper.startPage(pageNum,pageSize);
        List<Task> tasks = taskMapper.selectAllTask();
        PageInfo<Task> pageInfo = new PageInfo<>(tasks,5);
        return pageInfo;
    }


    /*
    发布任务
     */
    @Override
    public void insertTask(Task task) {
        taskMapper.insertTask(task);
    }


    /**
     *
     * @param taskId  个人中心  删除任务
     */
    @Override
    public void deleteByTaskId(Integer taskId)
    {
        taskMapper.deleteByTaskId(taskId);
    }

    @Override
    public PageInfo<Task> selectTaskByMarkId(Integer markId) {
        int pageNum = 1;
        int pageSize = 5;
        PageHelper.startPage(pageNum,pageSize);
        List<Task> tasks = taskMapper.selectByMark(markId);
        PageInfo<Task> pageInfo = new PageInfo<>(tasks,5);
        return pageInfo;
    }
    /**
     * 任务的发表评论details.jsp
     * @param taskComments
     */
    @Override
    public void insertTaskComments(Comment taskComments) {
        commentMapper.insertTaskComments(taskComments);
    }

    /**
     * 查找所有的任务评论
     * @return
     */
    @Override
    public PageInfo<Comment> findTaskComments(Integer id) {
        int pageNum=SysContext.getPageNum();//获取页码
        int pageSize=20;//每页5条
        PageHelper.startPage(pageNum, pageSize);//插件里面的方法 存放当前页码和每页几条数据
        List<Comment> comments= commentMapper.findTaskComments(id);
        PageInfo<Comment> pageInfo=new PageInfo<>(comments,5);
        return  pageInfo;
    }

    /**
     * sorl分词搜索加分页
     * @param title
     * @return
     */
    @Override
    public List<Task> findByTitles(String title,Pager pager) {
        List<Task> tasks = new ArrayList<>();
        int pageNum=SysContext.getPageNum();//获取页码
        int pageSize=5;//每页有5条
//        PageHelper.startPage(pageNum, pageSize);
////        PageInfo<Task> pageInfo=null;
        pager.setPageNum(pageNum);
        pager.setPageSize(pageSize);

        try {
            SolrQuery query = new SolrQuery();
            //设置查询条件
            query.setQuery("title:"+title);
            //设置分页
            //从哪一条开始查询 (pageNum-1)*pagesize
            query.setStart((pageNum-1)*pageSize);
            //查询条数 pageSize
            query.setRows(pageSize);
            //设置高亮
            query.setHighlight(true);
            //设置高亮字段 可以用逗号分开指定多个高亮字段
            query.set("hl.fl", "title");
            //查询

            QueryResponse response = client.query("question",query);
            //获得高亮数据
            Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
            Task task = null;
            Userinfo userinfo = null;
            //获得所有的文档集合
            SolrDocumentList documentList = response.getResults();
            pager.setDataCount((int)documentList.getNumFound());
            for (SolrDocument document : documentList) {
                task = new Task();
                String id = (String) document.getFieldValue("id");
                task.setId(Integer.parseInt(id));
                Integer userinfoId = (Integer) document.getFieldValue("userinfoId");
                task.setUserinfoId(userinfoId);
                task.setTitle(highlighting.get(id).get("title").get(0));
                task.setEnable(true);
                String pic=(String) document.getFirstValue("pic");
                task.setPic(pic);
                Integer markId = (Integer) document.getFieldValue("markId");
                task.setMarkId(markId);
                Date inputTime = (Date) document.getFieldValue("inputTime");
                if (inputTime != null) {
                    task.setInputTime(new Timestamp(inputTime.getTime()));
                }
                String info=(String) document.getFirstValue("info");
                task.setInfo(info);
                task.setBrowse((Integer) document.getFieldValue("browse"));
                task.setComments((Integer)document.getFieldValue("comments"));




                userinfo=userinfoMapper.findById(userinfoId);
                task.setUserinfo(userinfo);
                tasks.add(task);
            }
        } catch (SolrServerException e) {
        } catch (IOException e) {
        }

        return tasks;
    }

    /**
     *
     * @param id 个人中心首页  查看发布任务数量
     * @return
     */
    @Override
    public Integer findCountByUserId(Integer id)
    {
        return taskMapper.findCountByUserId(id);
    }

    /**
     *
     * @param task 个人中心 修改任务
     */
    @Override
    public void updateByTaskId(Task task)
    {
        taskMapper.updateByTaskId(task);
    }

    /**
     * 添加任务的评论(二级评论)
     * @param multistageComments
     */
    @Override
    public void insertTaskMultistageComments(Comment multistageComments) {
        commentMapper.insertTaskMultistageComments(multistageComments);
    }


    /**
     * 查找待接受和已经接受的任务
     * @param markId
     * @param
     * @return
     */
    @Override
    public PageInfo<Task> selectStayAccept(Integer markId) {
        int pageNum= SysContext.getPageNum();
        int pageSize=5;
        PageHelper.startPage(pageNum, pageSize);
        List<Task> tasks=taskMapper.selectStayAccept(markId);
        PageInfo<Task> pageInfo = new PageInfo<>(tasks, 5);
        return pageInfo;

    }


    /**
     *
     * @param userId
     * @param taskId   接受任务
     */
    @Override
    public void acceptTask(Integer userId, Integer taskId) {
        taskMapper.updateUserByTaskId(userId,taskId);
    }

    /**
     * 显示任务评论数 点击发布评论 评论数就加1；
     * @param id
     */
    @Override
    public void updateTaskComments(Integer id) {
        taskMapper.updateTaskComments(id);
    }


    //根据一级评论 查  二级评论
    @Override
    public List<Comment> findTaskMultistageComments(Integer id) {

//        return commentMapper.findByCommentId(id);
        return null;
    }

    @Override
    public void insertReject(Task task) {
       taskMapper.insertReject(task);
    }

    /**
     *
     * @param id  个人中心  完成的任务
     * @return
     */
    @Override
    public PageInfo<Task> selectFinishByUserId(Integer id) {
        int pageNum = SysContext.getPageNum();
        int pageSize = 5;
        PageHelper.startPage(pageNum,pageSize);
        List<Task> tasks= taskMapper.selectFinishByUserId(id);
        PageInfo<Task> pageInfo = new PageInfo<>(tasks,5);
        return pageInfo;

    }


}
